import React, {useEffect, useState} from 'react'
import { Form, Button, DatePicker,Input, Modal,Row, Col,Popconfirm,Select,message} from 'antd'
import { connect } from 'umi'
import moment from 'moment'
import {jobLevelTypeList,promotionTypeList,probationDayList} from "@/utils/constant";
import {getJobByOrgId} from "../service";
import store from 'store2';

const FormItem = Form.Item;
const {Option} = Select;

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

const AddForm = (props) => {
  const { onSubmit, onCancel,type, loading,record,visible,title,currentUser,global = {} } = props;
  const {options = {}} = global;
  const {jobLevel = []} = options;
  const [form] = Form.useForm();
  const [finalOrgTree, setFinalOrgTree] = useState([]);
  const [jobList, setJobList] = useState([]);
  const [jobLevelTemp,setJobLevelTemp] = useState([]);

  useEffect(() => {
    setFinalOrgTree([{title:currentUser.department,value:currentUser.depId}]);
    onChangeUnitId(currentUser.depId);
    onChangeJobLevelType(type === 'profession'?1:2);
    if(record){
      setJobLevelTemp(jobLevel);
      form.setFieldsValue({...record,applyTime:moment(record.applyTime),promotionDate:moment(record.promotionDate),
        jobLevelId:record.beforeJobLevelId,afterJobType:parseInt(record.afterJobType),
        afterUnitId:currentUser.depId,
        probationday:record.expeditionDays
      });
    }else if(currentUser){
      const fieldsValue = store(`personnel-promotion-` + type + `-` + currentUser.id);
      if(fieldsValue){
        form.setFieldsValue({...fieldsValue,promotionDate:moment(fieldsValue.promotionDate),applyTime:moment(fieldsValue.applyTime)});
      }else {
        form.setFieldsValue({
          ...currentUser, applyTime: moment(), jobLevelId: currentUser.jobLevelId.toString(),
          promotionType: type === 'profession' ? 1 : 2,
          afterJobType: type === 'profession' ? 1 : 2,
          afterUnitId: currentUser.depId
        })
      }
    }
  }, [visible])

  const recursiveSetSelectable = (list) => {
    if(list.length > 0){
      list.forEach(item => {
        if (item.children?.length>0){
          item.selectable = false;
          recursiveSetSelectable(item.children)
        }
      })
    }
  };

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({...fieldsValue,promotionKind:0,isSelf:1,promotionId:record && record.promotionId});
  };

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  };

  const onChangeUnitId = (id) => {
    getJobByOrgId(id).then((res) => {
      setJobList(res)
    })
  };

  const onChangeJobLevelType = (e) => {
    form.setFieldsValue({afterJobLevelId:undefined});
    if (e === 2) {
      setJobLevelTemp(jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK').reverse())
    } else {
      setJobLevelTemp(jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK').reverse())
    }
  };

  const onFormSave = async () => {
    const fieldsValue = await form.validateFields();
    store(`personnel-promotion-` + type + `-` + currentUser.id,fieldsValue);
    message.success("信息暂存成功！");
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyTime" label="申请日期">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="department" label="所属部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="现任岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobLevelType" label="现职级类型">
              <Select disabled={true}>
                {jobLevelTypeList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobLevelId" label="现职级">
              <Select disabled={true}>
                {
                  jobLevel.map((item, index) => {
                    return (
                      <Option value={item.id} key={item.name}>
                        {item.name}
                      </Option>
                    )
                  })
                }
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="afterUnitId" label="申请晋升部门" rules={[{required: true, message: '申请晋升部门不能为空'}]}>
              <Select placeholder="请选择" disabled={true} filterOption={filterOption}>
                {finalOrgTree && finalOrgTree.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.title}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="afterJobId" label="申请晋升岗位"  rules={[{required: true, message: '申请晋升岗位不能为空'}]}>
              <Select placeholder="请选择" showSearch filterOption={filterOption}>
                {jobList && jobList.map((item, index) => {
                  return (
                    <Option value={`${item.coidassignedjob}`} key={item.coidassignedjob}>
                      {item.cname}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="afterJobType" label="申请职级类型"  rules={[{required: true, message: '申请职级类型不能为空'}]}>
              <Select placeholder="请选择" disabled={true} showSearch filterOption={filterOption} onChange={onChangeJobLevelType}>
                {jobLevelTypeList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="afterJobLevelId" label="申请晋升职级"  rules={[{required: true, message: '申请晋升职级不能为空'}]}>
              <Select placeholder="请选择" filterOption={filterOption}>
                {
                  jobLevelTemp.map((item, index) => {
                    return (
                      <Option value={item.id} key={item.name}>
                        {item.name}
                      </Option>
                    )
                  })
                }
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="promotionDate" label='申请晋升日期' rules={[{required: true, message: '申请晋升日期不能为空'}]}>
              <DatePicker placeholder="请选择晋升日期" style={{width: '100%'}}/>
            </FormItem>
          </Col>
          <Col span={type === 'profession' ? 0 : 8}>
            <FormItem name="probationday" label="试用期期限" rules={type === 'profession' ? '' : [{required: true, message: '试用期期限不能为空'}]}>
              <Select placeholder="请选择" filterOption={filterOption}>
                {probationDayList.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="promotionType" label="晋升类型">
              <Select disabled={true} placeholder="请选择" filterOption={filterOption}>
                {promotionTypeList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button onClick={() => onFormSave()}>暂存</Button>
        <Popconfirm title={`确认发起晋级申请?`}
                    onConfirm={() => handleSubmit()}
                    okText="是" cancelText="否">
          <Button type="primary" loading={loading}>提交</Button>
        </Popconfirm>
      </>
    )
  };

  return (
    <Modal
      maskClosable={false}
      width={1280}
      destroyOnClose
      title={ title + `晋级`}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
};

export default connect(({global,user}) => ({
  currentUser: user.currentUser,
  global
}))(AddForm)
